package com.wolfalpha.utron.app;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.update.UmengUpdateAgent;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.MainActivity;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.net.ApiClient;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ImageUtils;
import com.wolfalpha.utron.utils.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidClassException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import easemob.applib.controller.HXSDKHelper;
import easemob.chatuidemo.Constant;
import easemob.chatuidemo.DemoHXSDKHelper;
import easemob.chatuidemo.db.UserDao;
import easemob.chatuidemo.domain.User;

/**
 * 应用处理，缓存处理
 *
 * @author Administrator
 */
@SuppressLint("HandlerLeak")
public class AppContext extends Application implements
        Thread.UncaughtExceptionHandler {

    public static final int NETTYPE_WIFI = 0x01;
    public static final int NETTYPE_CMWAP = 0x02;
    public static final int NETTYPE_CMNET = 0x03;

    private static final int CACHE_TIME = 60 * 60000;

    private static ApiClient apiClient;

    public static String[] CALLS = new String[]{"技术", "运营", "设计", "产品", "销售"};

    private Hashtable<String, Object> memCacheRegion = new Hashtable<String, Object>();

    private static AppContext instance;

    private UserInfo userInfo;


    private Handler unLoginHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                UIHelper.ToastMessage(AppContext.this,
                        getString(R.string.msg_login_error));
            }
        }
    };

    private boolean isDebug = false;

    public DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        apiClient = new ApiClient();


        int[] idArr = getResources().getIntArray(R.array.dirs_id);
        String[] nameArr = getResources().getStringArray(R.array.dirs_name);
        dirs = Arrays.asList(nameArr);

        //设置Thread Exception Handler
        Thread.setDefaultUncaughtExceptionHandler(this);
//
//
//        /**
//         * 初始化环信聊天
//         */
//        int pid = android.os.Process.myPid();
//        String processAppName = StringUtils.getAppName(this, pid);
//        // 如果app启用了远程的service，此application:onCreate会被调用2次
//        // 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
//        // 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process name就立即返回
//
//        if (processAppName == null || !processAppName.equalsIgnoreCase("com.wolfalpha.utron")) {
//            //"com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名
//
//            // 则此application::onCreate 是被service 调用的，直接返回
//            return;
//        }
//
//        EMChat.getInstance().init(this);
//        /**
//         * debugMode == true 时为打开，sdk 会在log里输入调试信息
//         * @param debugMode
//         * 在做代码混淆的时候需要设置成false
//         */
//        EMChat.getInstance().setDebugMode(true);//在做打包混淆时，要关闭debug模式，如果未被关闭，则会出现程序无法运行问题

        /**
         * this function will initialize the HuanXin SDK
         *
         * @return boolean true if caller can continue to call HuanXin related APIs after calling onInit, otherwise false.
         *
         * 环信初始化SDK帮助函数
         * 返回true如果正确初始化，否则false，如果返回为false，请在后续的调用中不要调用任何和环信相关的代码
         *
         * for example:
         * 例子：
         *
         * public class DemoHXSDKHelper extends HXSDKHelper
         *
         * HXHelper = new DemoHXSDKHelper();
         * if(HXHelper.onInit(context)){
         *     // do HuanXin related work
         * }
         */
        hxSDKHelper.onInit(this);

        /*友盟*/
        UmengUpdateAgent.setUpdateAutoPopup(false); //关闭自动弹出

        /*bugly SDK*/
        CrashReport.initCrashReport(this, "Fs0ONroSrMUYhZ1F", false);
    }

    /**
     * 获取环信SDK
     *
     * @return
     */
    public DemoHXSDKHelper getHxSDKHelper() {
        return hxSDKHelper;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        System.out.println("uncaughtException:");
        ex.printStackTrace();
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    /**
     * 初始化用户信息
     */
    public void initUserInfo(UserInfo uInfo) {
        this.userInfo = uInfo;
        saveObject(userInfo, "userInfo");
        hxSDKHelper.setHXId(userInfo.getId() + "");
    }

    public UserInfo getUserInfo() {
        return userInfo;
    }

    /**
     * 获取用户ID
     * <p/>
     * 失败 返回-1
     *
     * @return
     */
    public int getUserId() {
        if (userInfo != null) {
            return userInfo.getUser_id();
        } else {
            return -1;
        }
    }

    public static AppContext getInstance() {
        return instance;
    }

    public static ApiClient getApiClient() {
        if (apiClient != null) return apiClient;
        else {
            apiClient = new ApiClient();
            return apiClient;
        }

    }

    /**
     * 判断是否为调试
     *
     * @return
     */
    public boolean getDebug() {
        return isDebug;
    }

    /**
     * 设置调试模式
     *
     * @param debug
     */
    public void setDebug(boolean debug) {
        this.isDebug = debug;
    }

    private boolean logined = false;

    /**
     * 登陆成功后调用
     */
    public void doLogin() {
        setProperty("logined", "true");
        logined = true;
    }

    /**
     * 匿名登陆成功后调用
     */
    public void doAnonLogin() {
        setProperty("logined", "false");
        logined = false;
    }


    /**
     * 判断是否已经登录
     *
     * @return
     */
    public boolean getIsLogined() {
        logined = false;
        if (getProperty("logined") == null) {
            return false;
        } else {
            if (getProperty("logined").equals("true")) {
                logined = true;
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 退出
     */
    public void logout() {
        setProperty("logined", "false");
        logined = false;
    }

    /**
     * 判断是否连接网络
     *
     * @return
     */
    public boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    /**
     * 获取网络连接方式
     *
     * @return 1:wify 2-3 蜂窝
     */
    @SuppressLint("DefaultLocale")
    public int getNetworkType() {
        int netType = 0;
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            String extraInfo = networkInfo.getExtraInfo();
            if (!StringUtils.isEmpty(extraInfo)) {
                if (extraInfo.toLowerCase().equals("cmnet")) {
                    netType = NETTYPE_CMNET;
                } else {
                    netType = NETTYPE_CMWAP;
                }
            }
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = NETTYPE_WIFI;
        }
        return netType;
    }

    /**
     * 判断指定版本是否在本地兼容
     *
     * @param VersionCode
     * @return
     */
    public static boolean isMethodsCompat(int VersionCode) {
        int currentVersion = android.os.Build.VERSION.SDK_INT;
        return currentVersion >= VersionCode;
    }

    /**
     * 获取当前手机的SDK版本号
     *
     * @return
     */
    public static int getSDKVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    /**
     * 获取当前应用的信息
     *
     * @return
     */
    public PackageInfo getPackageInfo() {
        PackageInfo info = null;
        try {
            info = getPackageManager().getPackageInfo(getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }

    /**
     * 获取应用的版本Code
     *
     * @return
     */
    public int getAppVersionCode() {
        return getPackageInfo().versionCode;
    }

    /**
     * 获取应用的版本名
     *
     * @return
     */
    public String getAppVersionName() {
        return getPackageInfo().versionName;
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    public boolean isHttpsLogin() {
        String perf_httpslogin = getProperty(AppConfig.CONF_HTTPS_LOGIN);
        if (StringUtils.isEmpty(perf_httpslogin))
            return false;
        else
            return StringUtils.toBool(perf_httpslogin);
    }

    /**
     * 设置是否登录
     *
     * @param b
     */
    public void setConfigHttpsLogin(boolean b) {
        setProperty(AppConfig.CONF_HTTPS_LOGIN, String.valueOf(b));
    }

    /**
     * 清除所有Cookie
     */
    public void cleanCookie() {
        removeProperty(AppConfig.CONF_COOKIE);
    }

    /**
     * 判断读取缓存文件是否为空
     *
     * @param cachefile
     * @return
     */
    @SuppressWarnings("unused")
    private boolean isReadDataCache(String cachefile) {
        return readObject(cachefile) != null;
    }

    /**
     * 判断缓存是否存在
     *
     * @param cachefile
     * @return
     */
    private boolean isExistDataCache(String cachefile) {
        boolean exist = false;
        File data = getFileStreamPath(cachefile);
        if (data.exists())
            exist = true;
        return exist;
    }

    /**
     * 判断缓存是否失败
     *
     * @param cachefile
     * @return
     */
    public boolean isCacheDataFailure(String cachefile) {
        boolean failure = false;
        File data = getFileStreamPath(cachefile);
        if (data.exists()
                && (System.currentTimeMillis() - data.lastModified()) > CACHE_TIME)
            failure = true;
        else if (!data.exists())
            failure = true;
        return failure;
    }

    /**
     * 清除缓存文件夹
     *
     * @param dir
     * @return
     */
    @SuppressWarnings("unused")
    private int clearCacheFolder(File dir, long curTime) {
        int deletedFiles = 0;
        if (dir != null && dir.isDirectory()) {
            try {
                for (File child : dir.listFiles()) {
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, curTime);
                    }
                    if (child.lastModified() < curTime) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return deletedFiles;
    }

    /**
     * 内存缓存
     *
     * @param key
     * @param value
     */
    public void setMemCache(String key, Object value) {
        memCacheRegion.put(key, value);
    }

    /**
     * 获取内存缓存
     *
     * @param key
     * @return
     */
    public Object getMemCache(String key) {
        return memCacheRegion.get(key);
    }

    /**
     * 设置文件缓存
     *
     * @param key
     * @param value
     * @throws IOException
     */
    public void setDiskCache(String key, String value) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = openFileOutput("cache_" + key + ".data", Context.MODE_PRIVATE);
            fos.write(value.getBytes());
            fos.flush();
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 获取文件缓存
     *
     * @param key
     * @return
     * @throws IOException
     */
    public String getDiskCache(String key) throws IOException {
        FileInputStream fis = null;
        try {
            fis = openFileInput("cache_" + key + ".data");
            byte[] datas = new byte[fis.available()];
            fis.read(datas);
            return new String(datas);
        } finally {
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 清除app缓存
     */
    public void clearAppCache() throws IOException {
        //清除webview缓存
        File file = getCacheDir();
        if (file != null && file.exists() && file.isDirectory()) {
            for (File item : file.listFiles()) {
                item.delete();
            }
            file.delete();
        }
        deleteDatabase("webview.db");
        deleteDatabase("webview.db-shm");
        deleteDatabase("webview.db-wal");
        deleteDatabase("webviewCache.db");
        deleteDatabase("webviewCache.db-shm");
        deleteDatabase("webviewCache.db-wal");
        //清除数据缓存
//        clearCacheFolder(getFilesDir(), System.currentTimeMillis());
        clearCacheFolder(getCacheDir(), System.currentTimeMillis());
        //2.2版本才有将应用缓存转移到sd卡的功能
        if (isMethodsCompat(android.os.Build.VERSION_CODES.FROYO)) {
            clearCacheFolder(getExternalCacheDir(), System.currentTimeMillis());
        }
        //清除编辑器保存的临时内容
        Properties props = getProperties();
        for (Object key : props.keySet()) {
            String _key = key.toString();
            if (_key.startsWith("temp"))
                removeProperty(_key);
        }

        //删除头像
        ImageUtils.deleteImage(this, "user_head.jpg");
    }
//


    /**
     * 保存序列类
     *
     * @param ser
     * @param file
     * @throws IOException
     */
    public boolean saveObject(Serializable ser, String file) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = openFileOutput(file, MODE_PRIVATE);
            oos = new ObjectOutputStream(fos);
            oos.writeObject(ser);
            oos.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                oos.close();
            } catch (Exception e) {
            }
            try {
                fos.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * 读取序列类
     *
     * @param file
     * @return
     * @throws IOException
     */
    public Serializable readObject(String file) {
        if (!isExistDataCache(file))
            return null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = openFileInput(file);
            ois = new ObjectInputStream(fis);
            return (Serializable) ois.readObject();
        } catch (FileNotFoundException e) {
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof InvalidClassException) {
                File data = getFileStreamPath(file);
                data.delete();
            }
        } finally {
            try {
                ois.close();
            } catch (Exception e) {
            }
            try {
                fis.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    public boolean containsProperty(String key) {
        Properties props = getProperties();
        return props.containsKey(key);
    }

    public void setProperties(Properties ps) {
        AppConfig.getAppConfig(this).set(ps);
    }

    public Properties getProperties() {
        return AppConfig.getAppConfig(this).get();
    }

    public void setProperty(String key, String value) {
        AppConfig.getAppConfig(this).set(key, value);
    }

    public String getProperty(String key) {
        return AppConfig.getAppConfig(this).get(key);
    }

    public void removeProperty(String... key) {
        AppConfig.getAppConfig(this).remove(key);
    }

    public List<String> getDirs() {
        return dirs;
    }

    private List<String> dirs = new ArrayList<String>();


    /********************环信***********************/

    /**
     * 初始化环信好友列表
     */
    public void initializeContacts() {

//        EMGroupManager.getInstance().loadAllGroups();
        EMChatManager.getInstance().loadAllConversations();
        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).setContactList(((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList());


//        Map<String, User> userlist = new HashMap<String, User>();
//        // 添加user"申请与通知"
//        User newFriends = new User();
//        newFriends.setUsername(Constant.NEW_FRIENDS_USERNAME);
//        String strChat = "申请与通知";
//        newFriends.setNick(strChat);
//
//        userlist.put(Constant.NEW_FRIENDS_USERNAME, newFriends);
////        // 添加"群聊"
////        User groupUser = new User();
////        String strGroup = "群聊";
////        groupUser.setUsername(Constant.GROUP_USERNAME);
////        groupUser.setNick(strGroup);
////        groupUser.setHeader("");
////        userlist.put(Constant.GROUP_USERNAME, groupUser);
////
////        // 添加"Robot"
////        User robotUser = new User();
////        String strRobot = getResources().getString(R.string.robot_chat);
////        robotUser.setUsername(Constant.CHAT_ROBOT);
////        robotUser.setNick(strRobot);
////        robotUser.setHeader("");
////        userlist.put(Constant.CHAT_ROBOT, robotUser);robotUser
//
//        // 存入内存
//        ((DemoHXSDKHelper) HXSDKHelper.getInstance()).setContactList(userlist);
//        // 存入db
//        UserDao dao = new UserDao(this);
//        List<User> users = new ArrayList<User>(userlist.values());
//        dao.saveContactList(users);
    }

}
